﻿using System;
using System.Collections.Generic;
using System.Security.Permissions;

using Moe.ECamel.Common.Contracts;
using Moe.ECamel.Common.Entities;
using Moe.ECamel.Common.Security;
using Moe.ECamel.Server.BL;

namespace Moe.ECamel.Server.Services
{
	/// <summary>
	/// Service Interface for Items services.
	/// </summary>
	public class ItemService : ECamelService, IItemService
	{
		public ItemService()
			: base()
		{	
		}

		public ItemService(ECamelService caller)
			: base(caller)
		{
		}

		#region IItemService Members

		/// <summary>
		/// Searches for items matching the specified item.
		/// </summary>
		/// <param name="request"></param>
		/// <returns>Matching items.</returns>
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.ItemView)]
		public SearchItemsResponse SearchItems(SearchItemsRequest request)
		{
			// Execute operation via service BL:
			using (var bl = new ItemBL(GetReadOnlyDataContext()))
			{
				return bl.SearchItems(request);
			}
		}

		/// <summary>
		/// Creates a new item.
		/// </summary>
		/// <param name="item">Item details.</param>
		/// <returns>If successful - null, otherwise validation error.</returns>
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.ItemAdd)]
		public ECamelError CreateItem(Item item)
		{
			return CreateItems(new Item[] {item});
		}
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.ItemAdd)]
		public ECamelError CreateItems(IEnumerable<Item> items)
		{
			using (ItemBL bl = new ItemBL(GetReadWriteDataContext()))
			{
				foreach (var item in items)
				{
					ECamelError error = bl.CreateItem(item);
					if (error != null)
						return error;
				}
			}

			return SubmitChanges(null);
		}
		/// <summary>
		/// Updates an item.
		/// </summary>
		/// <param name="item">Item details.</param>
		/// <returns>If successful - null, otherwise validation error.</returns>
		[PrincipalPermission(SecurityAction.Demand, Role = Operations.ItemEdit)]
		public ECamelError UpdateItem(Item item)
		{
			ECamelError error;

			using (ItemBL bl = new ItemBL(GetReadWriteDataContext()))
			{
				error = bl.UpdateItem(item);
			}

			return SubmitChanges(error);
		}

		#endregion

		public Item GetItemById(int itemId)
		{
			using (var bl = new ItemBL(GetReadOnlyDataContext()))
			{
				return bl.GetItemById(itemId);
			}
		}
	}
}